"use client";

import { useContext, useEffect, useState } from "react";
import { UserCtx } from "../layout";
import { useRouter } from "next/navigation";
import itemsService from "@/app/services/items.service";
import Item from "@/shared/item";
import Link from "next/link";

export default function ManagePage() {
  const router = useRouter();
  const { user } = useContext(UserCtx);
  const [items, setItems] = useState<Item[]>([]);
  const [searchTerm, setSearchTerm] = useState<string>("");

  useEffect(() => {
    const l = async () => {
      const items = await itemsService.getAllItems();
      setItems(items);
      if (user?.role.toString() !== "ADMIN") return router.push("/");
    };

    l();
  }, []);

  const onSearch = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSearchTerm(event.target.value);
  };

  const filteredItems = items.filter(
    (item) =>
      item.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.description.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <section className="manage" style={{ flex: 2 }}>
      <h1 className="heading">
        Управление <span>меню</span>
      </h1>
      <div style={{ minWidth: "50%" }}>
        <div className="row" style={{ justifyContent: "space-between" }}>
          <Link href={"/manage/add"}>
            <input type="submit" value="Добавить позицию" className="btn" />
          </Link>
          <Link href={"/manage/categories"}>
            <input type="submit" value="Добавить категорию" className="btn" />
          </Link>
        </div>
        <div className="inputBox">
          <span className="fas fa-search"></span>
          <input
            type="text"
            placeholder="Поиск.."
            name="search"
            onChange={onSearch}
          />
        </div>
        <table className="ordersTable" style={{ width: "100%" }}>
          <thead>
            <tr>
              <th>Наименование</th>
              <th>Категория</th>
              <th>Описание</th>
              <th>Стоимость </th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {filteredItems.map((i) => (
              <tr>
                <td>{i.name}</td>
                <td>{i.category.name}</td>
                <td>{i.description.substring(0, 15) + "..."}</td>
                <td>{i.price} руб.</td>
                <td>
                  <Link href={`/manage/${i.id}`} passHref legacyBehavior>
                    <span
                      style={{ cursor: "pointer", fontSize: "25px" }}
                      className="fa  fa-cog"
                    ></span>
                  </Link>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </section>
  );
}
